package com.hk.kindheartedness;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.Calendar;
import java.util.Date;

/**
 * 医生挂号日期设置
 */
public class RegistrationSettingActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    private EditText setADoctorDate,setADoctorTime,setADoctorMoney,setADoctorCount;

//    登录医生ID
    private String loginDoctorId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_setting);
//        实例化
        dbOpenHelper = new DBOpenHelper(RegistrationSettingActivity.this, "db_kindheartedness", null, 1);
//         获取新增按钮控制权
        Button settingRegistrationBtn = findViewById(R.id.settingRegistrationBtn);
        settingRegistrationBtn.setOnClickListener(this);
//        获取各输入框的控制权
        setADoctorDate = findViewById(R.id.setADoctorDate);
        setADoctorDate.setHint("请选择就诊日期...");
//                日期选择触发器
        setADoctorDate.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    showDatePickDlg();
                    return true;
                }
                return false;
            }
        });
//                进入文本编辑框焦点触发日期选择器
        setADoctorDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showDatePickDlg();
                }
            }
        });
        setADoctorTime = findViewById(R.id.setADoctorTime);
        setADoctorTime.setHint("请选择就诊时间...");
        //                日期选择触发器
        setADoctorTime.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    showTimePickDlg();
                    return true;
                }
                return false;
            }
        });
//                进入文本编辑框焦点触发日期选择器
        setADoctorTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showTimePickDlg();
                }
            }
        });
        setADoctorMoney = findViewById(R.id.setADoctorMoney);
        setADoctorMoney.setHint("请选择就诊费用...");
        setADoctorCount = findViewById(R.id.setADoctorCount);
        setADoctorCount.setHint("请选择就诊人数...");

        Intent intent2 = getIntent();
        Bundle bundle = intent2.getExtras();
        loginDoctorId = bundle.getString("loginDoctorId");
        Log.i("当前登录医生ID：", loginDoctorId);

    }

    /**
     * 弹出日期选择框
     */
    private void showDatePickDlg() {
        Calendar calendar = Calendar.getInstance();
//        获取当前日期
        final int mYear = calendar.get(Calendar.YEAR);
        final int mMonth = calendar.get(Calendar.MONTH);
        final int mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(RegistrationSettingActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//                        判断选择年是否小于当前年
                        if (year < mYear) {
                            view.updateDate(mYear, mMonth, mDayOfMonth);
                            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"挂号日期仅可设置为当天后三天,请重新选择！");
                            return;
                        }
//                        判断选择月是否小于当前月
                        if (year == mYear && month < mMonth) {
                            view.updateDate(mYear, mMonth, mDayOfMonth);
                            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"挂号日期仅可设置为当天后三天,请重新选择！");
                            return;
                        }
//                        判断选择日是否小于或等于当前日
                        if (year == mYear && month == mMonth && dayOfMonth <= mDayOfMonth) {
                            view.updateDate(mYear, mMonth, mDayOfMonth);
                            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"挂号日期仅可设置为当天后三天,请重新选择！");
                            return;
                        }

                        /**
                         * 判断当前日期是否超过了后三天
                         */
//                        判断选择年是否大于当前年
                        if (year > mYear) {
                            view.updateDate(mYear, mMonth, mDayOfMonth);
                            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"挂号日期仅可设置为当天后三天,请重新选择！");
                            return;
                        }
//                        判断选择月是否>当前月
                        if (year == mYear && month > mMonth) {
                            view.updateDate(mYear, mMonth, mDayOfMonth);
                            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"挂号日期仅可设置为当天后三天,请重新选择！");
                            return;
                        }
//                        判断选择日是否大于后三日
                        int mDayOfMonth2 = mDayOfMonth+4;
                        if (year == mYear && month == mMonth && dayOfMonth >= mDayOfMonth2) {
                            view.updateDate(mYear, mMonth, mDayOfMonth);
                            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"挂号日期仅可设置为当天后三天,请重新选择！");
                            return;
                        }
                        month = month+1;
                        String s = String.valueOf(month);
                        if (s.length() == 1) {
                            s = "0"+s;
                        }
                        String day = String.valueOf(dayOfMonth);
                        if (day.length() == 1) {
                            day = "0"+day;
                        }
                        RegistrationSettingActivity.this.setADoctorDate.setText(year+"-"+s+"-"+day);
                    }
                },
                mYear,
                mMonth,
                mDayOfMonth);
        datePickerDialog.show();
    }

    /**
     * 弹出时间选择框
     */
    private void showTimePickDlg() {
        Calendar calendar = Calendar.getInstance();
//        获取当前时间
        final int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
        final int minute = calendar.get(Calendar.MINUTE);
        TimePickerDialog timePickerDialog = new TimePickerDialog(RegistrationSettingActivity.this,
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//                        时优化
                        String hourOfDayToStr = String.valueOf(hourOfDay);
                        if (hourOfDay == 0) {
                            hourOfDayToStr = "00";
                        }
//                        分钟优化
                        String minuteToStr = String.valueOf(minute);
                        if (minute == 0) {
                            minuteToStr = "00";
                        }
                        RegistrationSettingActivity.this.setADoctorTime.setText(hourOfDayToStr+":"+minuteToStr);
                    }
                },
                hourOfDay,
                minute,
                true);
        timePickerDialog.show();
    }

    /**
     * 按钮点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.settingRegistrationBtn:
//                设置新增挂号记录
                saveRegistrationSetting();
                break;
            default:
                break;
        }
    }

    /**
     * 新增医生设置挂号记录
     */
    private void saveRegistrationSetting() {
        String setADoctorDateToStr = setADoctorDate.getText().toString();
        String setADoctorTimeToStr = setADoctorTime.getText().toString();
        String setADoctorMoneyToStr = setADoctorMoney.getText().toString();
        String setADoctorCountToStr = setADoctorCount.getText().toString();
        Boolean check = checkDate(setADoctorDateToStr,setADoctorTimeToStr,setADoctorMoneyToStr,setADoctorCountToStr);
        if (check) {
            SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
            //                    封装需要新增的医生详情信息
            ContentValues contentValues = new ContentValues();
            contentValues.put("doctor_id",loginDoctorId);
            contentValues.put("registration_date",setADoctorDateToStr);
            contentValues.put("registration_time",setADoctorTimeToStr);
            contentValues.put("count",setADoctorCountToStr);
            contentValues.put("remaining_number",setADoctorCountToStr);
            contentValues.put("registration_money",setADoctorMoneyToStr);
            contentValues.put("create_time", DateUtil.dateString(new Date()));
            contentValues.put("update_time", DateUtil.dateString(new Date()));
            long settingRegistrationId = readableDatabase.insert("registration_setting", null, contentValues);
            if (settingRegistrationId > 0) {
                toast = ToastUtil.toastHint(toast, RegistrationSettingActivity.this, "新增挂号记录成功，请稍后查看！");
                return;
            }
        }

    }

    /**
     * 校验设置挂号记录参数
     * @param setADoctorDateToStr 就诊日期
     * @param setADoctorTimeToStr 就诊时间
     * @param setADoctorMoneyToStr 就诊费用
     * @param setADoctorCountToStr 就诊总人数
     * @return
     */
    private Boolean checkDate(String setADoctorDateToStr, String setADoctorTimeToStr, String setADoctorMoneyToStr, String setADoctorCountToStr) {
        if (setADoctorDateToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"就诊日期不能为空！");
            return false;
        }
        if (setADoctorTimeToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"就诊时间不能为空！");
            return false;
        }
        if (setADoctorMoneyToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"就诊费用不能为空！");
            return false;
        }
        if (setADoctorCountToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,RegistrationSettingActivity.this,"就诊人数不能为空！");
            return false;
        }

//        校验是否已经存在当前挂号记录
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursorRegistrationSetting = readableDatabase.query("registration_setting", null, "registration_date = ? and registration_time = ? ", new String[]{setADoctorDateToStr, setADoctorTimeToStr}, null, null, null);
        String id = null;
        while (cursorRegistrationSetting.moveToNext()) {
            id = cursorRegistrationSetting.getString(0);
        }
        if (id != null) {
            toast = ToastUtil.toastHint(toast, RegistrationSettingActivity.this, "当前挂号日期或时间已存在，请更换日期或时间！");
            return false;
        }
        return true;
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}